<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  ~   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
  ~
  ~   Licensed under the Apache License, Version 2.0 (the "License");
  ~   you may not use this file except in compliance with the License.
  ~   You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~   Unless required by applicable law or agreed to in writing, software
  ~   distributed under the License is distributed on an "AS IS" BASIS,
  ~   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~   See the License for the specific language governing permissions and
  ~   limitations under the License.
  ~
  --%>

<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<html>
<head>
    <title>管理集群节点</title>

    <style>
        .btn {
            margin: 0px 0px 0px 0;
        }

    </style>

    <script>

        $(function () {
            //toastr.warning("请先从下拉框中选择一个集群！");

            $.post("${ctx}/redis-api/getClusters", {}, function(data) {
                if (data.success){
                    var clusterList = $('#cluster-list');
                    loadDataToSelect(clusterList, data.result, 'id', 'clusterName');
                    clusterList.on('hidden.bs.select', function(){
                        if ($(this).val() != ""){
                            selectCluster($(this).val(), $(this).find("option:selected").text());//$(this).selectpicker('val')
                            $('#refresh-cluster').css('display','block');
                        }
                    });
                }
            });

            $('#refresh-cluster').click(function () {
                refreshCluster();
            })

            $('#replica-migration-btn').click(function(){
                replicaMigration();
            });
            
            $('#saveStandbyCluster').click(function () {
                var standbyId = $('#standbyId').selectpicker('val');
                if (standbyId == ''){
                    toastr.warning("请选择备用集群！");
                    return;
                }
                $.post("${ctx}/redis-api/setStandbyCluster", {
                    clusterId:$('#cluster-list').val(),
                    standbyId:standbyId
                }, function(data) {
                    if (data.success){
                        toastr.success("设置备用集群成功！");
                    }
                });
            });

        });

        function selectCluster(clusterId, clusterName){
            //$("#clusterName").html(' - ' + clusterName);
            $.post("${ctx}/redis-api/getClusterAndNodesInfo", {clusterId:clusterId}, function(data) {
                if (data.success){
                    var clusterInfo = data.result;
                    var masterNodes = clusterInfo.masterNodes;
                    var nodesData = [];
                    for (var i = 0; i < masterNodes.length; i++){
                    //for (var i in masterNodes){//ie8下有问题
                        var masterNode = masterNodes[i];
                        var slotsNum = masterNode.slotsLength;
                        //if (masterNode.slots){
                        //    slotsNum = masterNode.slots.length;
                        //}
                        nodesData.push({
                            id:masterNode.id,
                            nodeId:masterNode.nodeId,
                            masterNode:masterNode.ip+ ":"+masterNode.port,
                            slaveNode:"",
                            nodeState:masterNode.state,
                            slotsNum:slotsNum,
                            noFailover:masterNode.noFailover
                        });
                        var slaveNodesMap = masterNode.slaveNodesMap;
                        for (var slaveNodeId in slaveNodesMap){
                            var slaveNode = slaveNodesMap[slaveNodeId];
                            nodesData.push({
                                id:slaveNode.id,
                                nodeId:slaveNode.nodeId,
                                masterNode:"",
                                slaveNode:slaveNode.ip+ ":"+slaveNode.port,
                                nodeState:slaveNode.state,
                                slotsNum:"",
                                noFailover:slaveNode.noFailover
                            });
                        }
                    }
                    createNodeTable(nodesData);
                    var state = clusterInfo.state;
                    var color = 'green';
                    if (state != "ok"){
                        color = 'red';
                    }
                    if (state == 'ok'){
                        state = "正常"
                    }else{
                        state = "异常"
                    };
                    //$("#clusterName").html(' - ' + clusterName + "，状态：<span style='color:"+color+"'>"+state+"</span>");
                    $("#clusterName").html("<span style='color:"+color+"'>"+state+"</span>");
                    if (clusterInfo.type == 1){
                        $('#standby-cluster-config').css('display','none');
                        $('#clusterType').html('备用');
                    }else{
                        $('#standby-cluster-config').css('display','block');
                        $('#clusterType').html('主用');
                        $.post("${ctx}/redis-api/getStandbyClusterList", {clusterId:clusterId}, function(data) {
                            if (data.success){
                                var standbyId = $('#standbyId');
                                loadDataToSelect(standbyId, data.result, 'id', 'clusterName');
                                standbyId.selectpicker('val', clusterInfo.standbyId);
                            }
                        });

                    }
                }
            });
        }

        var nodeTable = null;
        function createNodeTable(data){
            if (nodeTable != null){
                nodeTable.bootstrapTable('load', data);
                return;
            }
            nodeTable = $('#nodes-info-table').bootstrapTable({
                uniqueId: "id",
                classes: "table table-no-bordered",
                striped: false,
                singleSelect: false,
                data: data,
                locale: "zh-US" ,
                rowStyle: function(row, index){
                    var css = {};
                    if (row.nodeState != 'CONNECTED'){
                        css = {color:'red'};
                    }
                    if (row.noFailover == 'yes'){
                        css = {color:'blue'};
                    }
                    if (row.masterNode != ''){
                        return {classes: 'active', css: css};
                    }else{
                        return {classes: '', css: css};
                    };
                },
                columns: [{
                    title: '主节点',
                    field: 'masterNode',
                    align: 'center',
                    valign: 'middle',
                    width: '15%'
                },{
                    title: '从节点',
                    field: 'slaveNode',
                    align: 'center',
                    valign: 'middle',
                    width: '15%'
                },{
                    title: '槽位个数',
                    field: 'slotsNum',
                    align: 'center',
                    valign: 'middle',
                    width: '10%'
                }, {
                    title: '连接状态',
                    field: 'nodeState',
                    align: 'center',
                    valign: 'middle',
                    width: '10%',
                    formatter:function(value, row, index){
                        if (value){
                            if (value == 'CONNECTED'){
                                return "正常";
                            }else{
                                return "异常";
                            }
                        }
                    }
                },{
                    title: '启停删除节点操作',
                    field: 'id',
                    align: 'left',
                    valign: 'middle',
                    width: '15%',
                    formatter:function(value, row, index){
                        var html = "";
                        if (row.nodeState){
                            if (row.nodeState == 'DISCONNECTED'){
                                html += '<button class="btn btn-default" href="#" onclick="operNode(\''+ row.id +
                                        '\', true)">启动</button> ';
                            }else{
                                html += '<button class="btn btn-default" onclick="operNode(\''+ row.id +
                                        '\', false)">停止</button> ';
                            }
                            html += '<button class="btn btn-default" onclick="removeNode(\''+ row.id +
                                    '\')">删除</button> ';
                        }

                        return html;
                    }
                },{
                    title: '是否允许自动接管主节点',
                    field: 'id',
                    align: 'left',
                    valign: 'middle',
                    width: '15%',
                    formatter:function(value, row, index){
                        var html = '';
                        if (row.noFailover){
                            html += "<span style='margin-right: 10px'>"+ (row.noFailover=="no"?"是":"否") +"</span>";
                            if (row.noFailover=="no"){
                                html += '<button class="btn btn-default" onclick="configNoFailover(\''+ row.id +
                                        '\', \'yes\')">设置禁止</button> ';
                            }else{
                                html += '<button class="btn btn-default"onclick="configNoFailover(\''+ row.id +
                                        '\', \'no\')">设置允许</button> ';
                            }
                        }
                        return html;
                    }
                },{
                    title: '手工接管或关联主节点操作',
                    field: 'id',
                    align: 'left',
                    valign: 'middle',
                    width: '20%',
                    formatter:function(value, row, index){
                        var html = '';
                        if (row.noFailover && row.masterNode == ''){
                                html += '<button class="btn btn-default" onclick="promoteMaster(\''+ row.id +
                                        '\')">接管</button> ';
                                html += '<button class="btn btn-default" onclick="promoteMaster(\''+ row.id +
                                        '\', true)">强制接管</button> ';
                                html += '<button class="btn btn-default" onclick="openReplicaMigrationWindow(\''+ row.id +
                                        '\')">关联</button> ';
                        }
                        return html;
                    }
                }]
            });
        }

        function operNode(id, isStart){
            if (id){
                $.post("${ctx}/redis-api/operClusterNode", {nodeId: id, isStart:isStart}, function(data) {
                    if (data.success){
                        var row = nodeTable.bootstrapTable('getRowByUniqueId', id);
                        var operName = isStart==true?'启动':'停止';
                        toastr.success("成功"+operName+"节点"+row.slaveNode+"，<br>如果状态没有变更，请过几秒后自行刷新查看！");
                        setTimeout(function(){
                            refreshCluster();
                        }, 2000);
                    }
                });
            }else{
                toastr.error('该节点存在异常，不能'+(isStart==true?'启动':'停止'));
            }
        }

        function promoteMaster(id, isForce){
            var params = {nodeId: id};
            if (isForce){
                params.isForce = isForce;
            }
            $.post("${ctx}/redis-api/promoteMaster", params, function(data) {
                if (data.success){
                    var row = nodeTable.bootstrapTable('getRowByUniqueId', id);
                    toastr.success("节点"+row.slaveNode+"成功切换为主节点，<br>如果状态没有变更，请过几秒后自行刷新查看！");
                    setTimeout(function () {
                        refreshCluster();
                    }, 3000);
                }
            });

        }

        function openReplicaMigrationWindow(id){
            var form = $('#replica-migration-form');
            form.find('[name="slaveNodeId"]').val(id);
            var row = nodeTable.bootstrapTable('getRowByUniqueId', id);
            form.find('#slaveNode').text(row.slaveNode);
            var masterNode = form.find('[name="masterNodeId"]');
            masterNode.empty();
            var data = nodeTable.bootstrapTable('getData');
            for (var i = 0; i < data.length; i++){
                if (data[i].masterNode != ''){
                //if (data[i].masterNode != '' && data[i].nodeState == 'CONNECTED'){
                    masterNode.append('<option value="'+data[i].nodeId+'">'+data[i].masterNode+'</option>');
                }
            }
            masterNode.selectpicker('refresh');
            $('#replica-migration-window').modal('show');
        }


        function replicaMigration(){
            var form = $('#replica-migration-form');
            if (!form.valid()) {
                return false;
            }
            $.post("${ctx}/redis-api/replicaMigration", form.serializeArray(), function(data) {
                if (data.success){
                    $('#replica-migration-window').modal('hide');
                    var row = nodeTable.bootstrapTable('getRowByUniqueId', form.find('[name="slaveNodeId"]').val());
                    toastr.success("节点"+row.slaveNode+"成功切换为主节点，<br>如果状态没有变更，请过几秒后自行刷新查看！");
                    setTimeout(function () {
                        refreshCluster();
                    }, 3000);
                }
            });
        }


        function configNoFailover(id, value){
            var params = {nodeId:id, param:'cluster-slave-no-failover',value:value};
            $.post("${ctx}/redis-api/configSet", params, function(data) {
                if (data.success){
                    var row = nodeTable.bootstrapTable('getRowByUniqueId', id);
                    toastr.success("节点"+row.slaveNode+"成功设置"+(value=='no'?'允许':'禁止')+"自动接管主节点！");
                    refreshCluster();
                }
            });
        }

        function refreshCluster(){
            var clusterList = $('#cluster-list');
            selectCluster(clusterList.val(), clusterList.find("option:selected").text());
        }

        function removeNode(nodeId) {
            if (nodeId){
                var row = nodeTable.bootstrapTable('getRowByUniqueId', nodeId);
                if (row.nodeState && row.nodeState == 'DISCONNECTED'){
                    toastr.warning("该节点状态异常，不能删除！");
                    return;
                }
                var index = layer.confirm('确认删除节点'+row.masterNode+row.slaveNode+'？', {
                    btn: ['确定','取消'], title: '删除确认', icon: 3
                }, function(){
                    layer.close(index);
                    $.post("${ctx}/redis-api/removeNodeFromCluster", {nodeId:nodeId}, function(data) {
                        if (data.success) {
                            toastr.success("节点删除成功！");
                            selectCluster($('#cluster-list').val());
                        }
                    }, "json");
                }, function(){
                });

            }else{
                toastr.error('该节点存在异常，不能删除！');
            }
        }

        function loadDataToSelect(selectEle, data, valueName, textName){
            selectEle.empty();
            for (var i = 0; i < data.length; i++){
                selectEle.append('<option value="'+data[i][valueName]+'">'+data[i][textName]+'</option>');
            }
            selectEle.selectpicker('refresh');
        }



    </script>
</head>

<body>

<div class="page-title">
    <div class="btn-group pull-right">
        <%--<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">选择集群<span class="caret"></span></button>--%>
        <%--<ul class="dropdown-menu dropdown-menu-right" id="cluster-list">--%>
        <%--</ul>--%>
        <select id="cluster-list" class="selectpicker show-tick" title="请选择集群" data-live-search="true" data-size="5">
        </select>
    </div>
    <h3>维护集群和节点</h3>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="widget-container fluid-height">
            <div class="heading" style="vertical-align: middle">
                <i class="icon-info"></i><span>集群信息</span>
            </div>
            <div class="widget-content padded">
                <div class="row form-horizontal">
                    <div class="col-md-3">
                        <label class="col-md-4 control-label" style="text-align: right; padding-right: 0px">集群状态：</label>
                        <span class="col-md-8" id="clusterName" style="padding-top: 7px"></span>
                    </div>
                    <div class="col-md-3">
                        <label class="col-md-4 control-label" style="text-align: right; padding-right: 0px">集群类型：</label>
                        <span class="col-md-4" id="clusterType" style="padding-top: 7px"></span>
                    </div>
                    <div class="col-md-5" id="standby-cluster-config" style="display: none">
                        <label class="col-md-2 control-label" style="text-align: right; padding-right: 0px">备用集群：
                        </label>
                        <div class="col-md-10">
                            <select id="standbyId" name="standbyId" class="selectpicker show-tick" title="请选择备用集群"
                                    data-live-search="true" data-size="5" required>
                            </select>
                            <button class="btn btn-default" type="button" id="saveStandbyCluster">设置</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <div class="widget-container fluid-height">
            <div class="heading" style="vertical-align: middle">
                <i class="icon-tasks"></i><span>主从节点信息列表</span>
                <button type="button" class="btn btn-primary pull-right" id="refresh-cluster" style="display: none">刷新</button>
            </div>
            <div class="widget-content padded text-center">
                <table class="table" id="nodes-info-table">
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="replica-migration-window" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog" style="width: 400px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">关联主节点</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="replica-migration-form">
                    <div class="form-group">
                        <label class="col-md-3 control-label">从节点：</label>
                        <div class="col-md-8">
                            <label class="control-label" id="slaveNode"></label>
                            <input id="slaveNodeId" name="slaveNodeId" type="hidden">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 control-label" for="masterNodeId">主节点：</label>
                        <div class="col-md-8">
                            <select id="masterNodeId" name="masterNodeId" class="selectpicker show-tick" title="请选择需要关联的主节点"
                                    data-live-search="true" data-size="5" required>
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="replica-migration-btn">关联</button>
                <button type="button". class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>


</body>
</html>
